package com.earl.spider.util;

import java.io.*;
import java.util.Properties;

public class PropUtil {
    public final static String config = FilePath.userHome + "\\spider.txt";

    public static String readConfig(String key) {
        return read(config, key);
    }

    public static String read(String filePath, String key) {
        File file = new File(filePath);
        Properties prop = new Properties();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            //prop.load(new InputStreamReader(fis, "GB2312"));
            prop.load(fis);
            return prop.getProperty(key);
        } catch (IOException e) {
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static boolean writeConfig(String key, String value) {
        return write(config, key, value);
    }

    public static boolean write(String filePath, String key, String value) {
        File file = new File(filePath);
        Properties prop = new Properties();
        FileInputStream fis = null;
        OutputStream fos = null;
        try {
            if (!file.exists()) file.createNewFile();
            fis = new FileInputStream(file);
            prop.load(fis);
            fos = new FileOutputStream(file);
            prop.setProperty(key, value);
            //prop.store(new OutputStreamWriter(fos, "UTF-8"), "write " + key);
            prop.store(fos, "write " + key);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

}
